package ftp

import (
	"gin/model"
	"strconv"
	"time"
)

type DataUserS struct {
	DataUserM    *model.DataUserM
	DataLogin    *model.DataLoginM
	DataEconomyM *model.DataEconomyM
	DataBankM    *model.DataBankM
}

func NewDataUserS() *DataUserS {
	return &DataUserS{
		model.NewDataUserM(),
		model.NewDataLoginM(),
		model.NewDataEconomyM(),
		model.NewDataBankM(),
	}
}

// 用户数据更新
func (p *DataUserS) EventUserListData(ftpInfoId int64) []model.DataUser {
	var dataTime int64

	//加载到本地数据
	UserData := p.DataUserM.GetUserList(ftpInfoId)
	//fmt.Println(UserData)
	//第一次启动没有数据 就设定为0
	if len(UserData) > 0 {
		//根据最新的时间来过滤查询 避免重复数据
		dataTime = UserData[0].LoginTime
	} else {
		dataTime = 0
	}
	//根据最新记录时间来获取比最新记录时间还早的数据为 新增数据
	loginData := p.DataLogin.GetLoginList(ftpInfoId, dataTime)

	if len(loginData) > 0 {

		var UserDataArr []model.DataUser
		for _, login := range loginData {
			saveUserData := model.DataUser{
				FtpInfoId:     ftpInfoId,
				GameId:        login["game_id"].(int64),
				GameName:      login["game_name"].(string),
				SteamId:       login["steam_id"].(string),
				RegTime:       login["min_logtime"].(int64),
				OnlineStatus:  1,
				LoginTime:     login["max_logtime"].(int64),
				CreatedStatus: true,
			}
			//新增数据到本地数据
			UserData = append(UserData, saveUserData)
		}

		//在线与离线状态监测
		loginData = p.DataLogin.GetLoginOutList(ftpInfoId, dataTime)

		for key, User := range UserData {
			for _, login := range loginData {
				//fmt.Println(User.SteamId, login["steam_id"].(string), User.SteamId == login["steam_id"].(string))

				if User.SteamId == login["steam_id"].(string) {
					//fmt.Println(User.LoginTime, login["max_logtime"].(int64), User.LoginTime <= login["max_logtime"].(int64))
					if login["max_logtime"].(int64) >= User.LoginTime {
						//如果登录时间小于离线时间 则设定为离线  （默认设定的在线）
						UserData[key].OnlineStatus = 0
					}
					UserData[key].OfflineTime = login["max_logtime"].(int64)
					break

				}
			}
		}

		now := time.Now()
		unixTime := now.Unix()
		//计算登录时间超过8小时的 设定为离线  一般 维护时间就8小时  后期添加一个维护时间设定
		var overtime int64
		overtime = 8 * 3600
		for key, User := range UserData {
			//fmt.Println("666", unixTime, User.LoginTime, (unixTime-User.LoginTime) > overtime)
			if User.OnlineStatus == 1 && (unixTime-User.LoginTime) > overtime {
				UserData[key].OfflineTime = unixTime
				UserData[key].OnlineStatus = 0
				UserData[key].UpdatedStatus = true
			}

			//新增数据存入数据库处理
			if User.CreatedStatus {
				UserData[key].CreatedStatus = false
				UserData[key].UpdatedStatus = false
				//存入数据库数据
				UserDataArr = append(UserDataArr, UserData[key])
			}
		}
		p.DataUserM.InsertUserData(UserDataArr)
	}

	//新增用户加入到数据库

	return UserData
}

// 用户银行 交易 数据更新
func (p *DataUserS) EventUserEconnomyData(ftpInfoId int64, UserData *[]model.DataUser) {

	//银行数据更新处理
	bankData := p.DataBankM.GetUserBankData(ftpInfoId)
	for key, user := range *UserData {
		for _, bank := range bankData {
			if bank.SteamId == user.SteamId && bank.LogTime > user.EconnomyTime {
				Balance, _ := strconv.ParseInt(bank.Balance, 10, 64)
				if Balance > 99999999 {
					Balance = 99999999
				}
				(*UserData)[key].Balance = Balance
				(*UserData)[key].BankCrad = bank.AccountCardNum
				(*UserData)[key].EconnomyTime = bank.LogTime
				(*UserData)[key].UpdatedStatus = true
			}
		}
	}

	//交易数据更新处理
	economyData := p.DataEconomyM.GetUserEconomyData(ftpInfoId)

	for key, user := range *UserData {
		for _, economy := range economyData {
			if economy.SteamId == user.SteamId && economy.LogTime > user.EconnomyTime {

				Balance, _ := strconv.ParseInt(economy.EndBalance, 10, 64)
				Gold, _ := strconv.ParseInt(economy.EndGold, 10, 64)
				if Balance > 99999999 {
					Balance = 99999999
				}

				if Gold > 99999999 {
					Gold = 99999999
				}
				(*UserData)[key].Balance = Balance
				(*UserData)[key].Gold = Gold
				(*UserData)[key].EconnomyTime = economy.LogTime

				(*UserData)[key].UpdatedStatus = true
			}
		}
	}

	//变动数据更新
	var newUserData []model.DataUser
	//新增用户加入到数据库
	for key3, user := range *UserData {
		if user.UpdatedStatus {
			(*UserData)[key3].UpdatedStatus = false
			newUserData = append(newUserData, user)
		}
	}

	p.DataUserM.UpdateUserData(ftpInfoId, newUserData)
}

// 实时登录用户数据处理
func (p *DataUserS) EventLoginDataUpdate(newLoginData []model.DataLogin, userList *[]model.DataUser, ftpInfoId int64) {

	var index int
	//过滤数据 取 logged in at  数据 中 steam 最相同 且  登录时间最大的  按  加载事件处理

	//数组排序 把登录的 放前面
	newLoginDataList := FilterAndDeduplicate(newLoginData, "logged in at")

	for _, LoginData := range newLoginDataList {

		index = -1

		for i2, user := range *userList {
			if user.SteamId == LoginData.SteamId {
				index = i2
				break
			}
		}

		if index == -1 {
			//新增
			loginUser := model.DataUser{
				FtpInfoId:     ftpInfoId,
				LogTime:       LoginData.LogTime,
				SteamId:       LoginData.SteamId,
				GameId:        LoginData.GameId,
				GameName:      LoginData.GameName,
				LoginTime:     LoginData.LogTime,
				RegTime:       LoginData.RegTime,
				OnlineStatus:  1,
				CreatedStatus: true,
			}
			*userList = append(*userList, loginUser)
		} else {
			(*userList)[index].LoginTime = LoginData.LogTime
			(*userList)[index].OnlineStatus = 1
			//用户改名
			if (*userList)[index].GameName != LoginData.GameName {
				(*userList)[index].GameName = LoginData.GameName
			}
			(*userList)[index].UpdatedStatus = true
		}

	}

	LoginOutData := FilterAndDeduplicate(newLoginData, "logged out at")
	for _, LoginOut := range LoginOutData {
		index = -1
		for i2, user := range *userList {
			if user.SteamId == LoginOut.SteamId {
				index = i2
				break
			}
		}

		if index == -1 {
			//不存在用户就跳过
			continue
		}
		//离线时间大于登录时间才处理
		if LoginOut.LogTime >= (*userList)[index].LoginTime {
			(*userList)[index].OnlineStatus = 0
		}
		//获得最新的离线时间
		if (*userList)[index].OfflineTime < LoginOut.LogTime {
			(*userList)[index].OfflineTime = LoginOut.LogTime
			(*userList)[index].UpdatedStatus = true
		}
	}

	now := time.Now()
	unixTime := now.Unix()
	//计算登录时间超过8小时的 设定为离线  一般 维护时间就8小时  后期添加一个维护时间设定
	var overtime int64
	overtime = 8 * 3600
	for key, User := range *userList {
		//fmt.Println("666", unixTime, User.LoginTime, (unixTime-User.LoginTime) > overtime)
		if User.OnlineStatus == 1 && (unixTime-User.LoginTime) > overtime {
			(*userList)[key].OfflineTime = unixTime
			(*userList)[key].OnlineStatus = 0
			(*userList)[key].UpdatedStatus = true
		}
	}

	//超过12小时设定为离线

}

// 登录数据筛选和去重的函数
func FilterAndDeduplicate(logins []model.DataLogin, typeStr string) []model.DataLogin {
	// 使用一个字典来存储每个 SteamId 对应的最大 LogTime 和相应的 DataLogin
	steamIdMap := make(map[string]model.DataLogin)

	for _, login := range logins {
		if login.LoginType == typeStr {
			if existingLogin, exists := steamIdMap[login.SteamId]; exists {
				// 如果该 SteamId 已存在，比较 LogTime，更新为最大值
				if login.LogTime > existingLogin.LogTime {
					//储存注册时间  避免每次被覆盖 第一次空数据 走 else逻辑
					RegTime := steamIdMap[login.SteamId].RegTime
					steamIdMap[login.SteamId] = login

					newLogin := steamIdMap[login.SteamId]
					newLogin.RegTime = RegTime
					steamIdMap[login.SteamId] = newLogin

				}
				//fmt.Println("11111", steamIdMap[login.SteamId])
				//修改注册时间  不能直接修改map里的值
				if login.RegTime < existingLogin.RegTime {

					newLogin := steamIdMap[login.SteamId]
					newLogin.RegTime = login.RegTime
					steamIdMap[login.SteamId] = newLogin
				}

			} else {
				// 如果该 SteamId 不存在，则直接添加
				steamIdMap[login.SteamId] = login
			}
		}
	}

	// 将结果转换为切片
	var result []model.DataLogin
	for _, login := range steamIdMap {
		result = append(result, login)
	}

	return result
}

// 银行实时数据处理
func (p *DataUserS) EventBankDataUpdate(BankArr []model.DataBank, UserList *[]model.DataUser) {
	newBankArr := FilterAndDeduplicateBank(BankArr, "purchased")
	var index int
	for _, bank := range newBankArr {
		index = -1

		for i2, user := range *UserList {
			if user.SteamId == bank.SteamId {
				index = i2
				break
			}
		}

		if index == -1 {
			//不存在用户就跳过
			continue
		}

		if bank.LogTime > (*UserList)[index].EconnomyTime {
			Balance, _ := strconv.ParseInt(bank.Balance, 10, 64)
			if Balance > 99999999 {
				Balance = 99999999
			}
			(*UserList)[index].EconnomyTime = bank.LogTime
			(*UserList)[index].Balance = Balance
			(*UserList)[index].BankCrad = bank.AccountCardNum
			(*UserList)[index].UpdatedStatus = true
		}

		//优先监控交易数据 如果 没有卡号数据 就再次检测卡号数据填入 补齐卡号数据
		if (*UserList)[index].BankCrad == "" && bank.AccountCardNum != "" {
			(*UserList)[index].BankCrad = bank.AccountCardNum
			(*UserList)[index].UpdatedStatus = true
		}
	}

}

// 银行数据筛选和去重的函数
func FilterAndDeduplicateBank(logins []model.DataBank, typeStr string) []model.DataBank {
	// 使用一个字典来存储每个 SteamId 对应的最大 LogTime 和相应的 DataLogin
	steamIdMap := make(map[string]model.DataBank)

	for _, login := range logins {
		if login.EventType == typeStr {
			if existingLogin, exists := steamIdMap[login.SteamId]; exists {
				// 如果该 SteamId 已存在，比较 LogTime，更新为最大值
				if login.LogTime > existingLogin.LogTime {
					steamIdMap[login.SteamId] = login
				}
			} else {
				// 如果该 SteamId 不存在，则直接添加
				steamIdMap[login.SteamId] = login
			}
		}
	}

	// 将结果转换为切片
	var result []model.DataBank
	for _, bank := range steamIdMap {
		result = append(result, bank)
	}

	return result
}

// 交易实时数据处理
func (p *DataUserS) EventEconomyDataUpdate(DataEconomyArr []model.DataEconomy, UserList *[]model.DataUser) {
	newDataEconomyArr := FilterAndDeduplicateEconomy(DataEconomyArr)
	var index int
	for _, economy := range newDataEconomyArr {
		index = -1

		for i2, user := range *UserList {
			if user.SteamId == economy.SteamId {
				index = i2
				break
			}
		}

		if index == -1 {
			//不存在用户就跳过
			continue
		}

		if economy.LogTime > (*UserList)[index].EconnomyTime {
			Balance, _ := strconv.ParseInt(economy.EndBalance, 10, 64)
			Gold, _ := strconv.ParseInt(economy.EndGold, 10, 64)
			if Balance > 99999999 {
				Balance = 99999999
			}

			if Gold > 99999999 {
				Gold = 99999999
			}
			(*UserList)[index].EconnomyTime = economy.LogTime
			(*UserList)[index].Balance = Balance
			(*UserList)[index].Gold = Gold
			(*UserList)[index].UpdatedStatus = true
		}
	}
}

// 交易数据筛选和去重的函数
func FilterAndDeduplicateEconomy(logins []model.DataEconomy) []model.DataEconomy {
	// 使用一个字典来存储每个 SteamId 对应的最大 LogTime 和相应的 DataLogin
	steamIdMap := make(map[string]model.DataEconomy)

	for _, login := range logins {
		if existingLogin, exists := steamIdMap[login.SteamId]; exists {
			// 如果该 SteamId 已存在，比较 LogTime，更新为最大值
			if login.LogTime > existingLogin.LogTime {
				steamIdMap[login.SteamId] = login
			}
		} else {
			// 如果该 SteamId 不存在，则直接添加
			steamIdMap[login.SteamId] = login
		}
	}

	// 将结果转换为切片
	var result []model.DataEconomy
	for _, data := range steamIdMap {
		result = append(result, data)
	}

	return result
}

// 保存更新用户数据
func (p *DataUserS) EventSaveUserData(ftpInfoId int64, UserList *[]model.DataUser) {
	var saveUserArr []model.DataUser
	for key, user := range *UserList {
		if user.CreatedStatus {
			saveUserArr = append(saveUserArr, user)
			(*UserList)[key].UpdatedStatus = false
			(*UserList)[key].CreatedStatus = false
		}
	}
	p.DataUserM.InsertUserData(saveUserArr)

	//变动数据更新
	var newUserData []model.DataUser
	//新增用户加入到数据库
	for key3, user := range *UserList {
		if user.UpdatedStatus {
			(*UserList)[key3].UpdatedStatus = false
			newUserData = append(newUserData, user)
		}
	}

	p.DataUserM.UpdateUserData(ftpInfoId, newUserData)

}
